package cn.yto.print.utils;

import cn.yto.print.config.CaffeineCacheConfig;
import cn.yto.print.constants.AssistantConstants;
import cn.yto.print.model.response.PrintTaskResponse;
import com.github.benmanes.caffeine.cache.Cache;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.List;

public class ExpiredMsgUtil {

    /**
     * 新增超时任务消息
     */
    public static void addExpiredMessage(PrintTaskResponse response) {
        if (null == response || StringUtils.isEmpty(response.getSessionId())) {
            return;
        }

        Cache<String, List<PrintTaskResponse>> expiredCache = CaffeineCacheConfig.getExpiredCache();
        List<PrintTaskResponse> printTaskResponses = expiredCache.getIfPresent(response.getSessionId());
        if (CollectionUtils.isEmpty(printTaskResponses)) {
            expiredCache.put(response.getSessionId(), Lists.newArrayList(response));
        } else {
            printTaskResponses.add(response);
            expiredCache.put(response.getSessionId(), printTaskResponses);
        }
    }

    public static void removeExpiredMessage(String sessionId) {
        if (StringUtils.isEmpty(sessionId)) {
            return;
        }
        CaffeineCacheConfig.getExpiredCache().invalidate(sessionId);
    }

    /**
     * 处理新会话消息
     */
    public static void handleHistoryResponse(Session session) {
        String sessionId = (String) session.getUserProperties().get(AssistantConstants.SESSION_ID);
        List<PrintTaskResponse> printTaskResponses = CaffeineCacheConfig.getExpiredCache().getIfPresent(sessionId);
        if (CollectionUtils.isNotEmpty(printTaskResponses)) {
            printTaskResponses.forEach(printTaskResponse -> {
                WebSocketUtil.sendSocketMessage(session, printTaskResponse);
            });
            removeExpiredMessage(sessionId);
        }
    }

}
